package immutablecollections.textboxes;

import immutablecollections.exceptions.*;
import immutablecollections.misc.*;
import java.util.*;

public class TopDownBox extends TextBox
{

    final private  List<TextBox> boxes;

    public static TopDownBox with(TextBox... boxes)
    {
        return withAll(Arrays.asList(boxes));
    }

    public static TopDownBox withAll(Collection<? extends TextBox> boxes)
    {
        int w = 0;
        int h = 0;
        for (TextBox b : boxes)
        {
            w = Math.max(w, b.getWidth());
            h = h + b.getHeight();
        }
        return new TopDownBox(w, h, boxes);
    }

    private TopDownBox(int w, int h, Collection<? extends TextBox> boxes)
    {
        super(w, h);
        this.boxes = new ArrayList<TextBox>(boxes);
    }

    public String getLine(int index)
    {
        if (index > getHeight())
        {
            return TextUtils.repeat(" ", getWidth());
        }

        int count = 0;
        for (TextBox b : boxes)
        {
            for (int i = 1; i <= b.getHeight(); i++)
            {
                count++;
                if (count == index)
                {
                    return TextUtils.pad(b.getLine(i), getWidth());
                }
            }
        }
        throw new InvalidStateException("You can't get here");
    }
}
